<?php
/**
 * Description of Category
 *
 * @author Lukas Normantas
 */
class Catalog_Model_Category extends Doctrine_Record
{
    protected $_categoryForm = null;

    public function setTableDefinition()
    {
        $this->setTableName('catalog_categories');
        $this->hasColumn('title', 'string', 255);
        $this->hasColumn('active', 'boolean', 25);
    }

    public function setUp()
    {
        $this->actAs('NestedSet');
        $this->actAs('Timestampable');
    }

    static protected function _ensureTreeHasRoot(Doctrine_Tree $tree)
    {
        if ( ! $tree->fetchTree() ){
            $category = new Catalog_Model_Category();
            $category->title = 'Catalog';
            $category->active = 1;
            $category->save();
            $tree->createRoot($category);
        }
    }

    public function getAdminSubcategoryList()
    {
        $category = Doctrine::getTable('Catalog_Model_Category')->find($this->id);
        $children = $category->getNode()->getChildren();
        return $children;
    }

    public function getActiveSubcategoryList()
    {
        $q = Doctrine_Query::create()
           ->select( 'c.*')
           ->from('Catalog_Model_Category c')
           ->where('active = ?', 1);
        $this->getTable()->getTree()->setBaseQuery($q);
        $children = $this->getNode()->getChildren();
        if ( ! $children) return false;
        return $children->toArray();
    }

    /*
     * Fetches paginator from active products with active specials of $this category
     */
    public function getActiveProductPaginator($current_page)
    {
        $q = Doctrine_Query::create()
           ->select('c.*, p.*, s.*')
           ->from( 'Catalog_Model_Product p' )
           ->leftJoin( 'p.Category c' )
           ->leftJoin( 'p.Specials s ON s.product_id = p.id '
                       .'AND s.start_at <= CURRENT_DATE AND s.end_at>=CURRENT_DATE')
           ->addWhere('p.active = ?', 1)
           ->andWhere('p.category_id = ?', $this->id )
           ->orderBy('p.created_at DESC' );
        $results_per_page = 10;
        $doctrinePager = new Doctrine_Pager($q, $current_page, $results_per_page);
        $zendPaginator = Areal_Paginator::build($doctrinePager);
        return $zendPaginator;
    }


    static public function getCategoryAdminMenuTree()
    {
        $treeObject = Doctrine::getTable('Catalog_Model_Category')->getTree();
        self::_ensureTreeHasRoot($treeObject);
        $q = Doctrine_Query::create()
            ->select('c.*')
            ->addSelect('(SELECT COUNT(p.id) FROM Catalog_Model_Product p WHERE p.category_id= c.id LIMIT 1) AS product_count')
            ->from('Catalog_Model_Category c');
        $treeObject->setBaseQuery($q);
        foreach ($treeObject->fetchRoots() as $rootCategory) {}
        return $rootCategory;
    }

    static public function getCategoryMenuTree()
    {
        $treeObject = Doctrine::getTable('Catalog_Model_Category')->getTree();
        self::_ensureTreeHasRoot($treeObject);
        $q = Doctrine_Query::create()
            ->from('Catalog_Model_Category c')
            ->where('active = ?', 1);
        $treeObject->setBaseQuery($q);
        foreach ($treeObject->fetchRoots() as $rootCategory) {}
        return $rootCategory;
    }

    static public function getCategorySelectData()
    {
        $treeObject = Doctrine::getTable('Catalog_Model_Category')->getTree();
        self::_ensureTreeHasRoot($treeObject);
        $q = Doctrine_Query::create()->from('Catalog_Model_Category c');
        $treeObject->setBaseQuery($q);
        $data = array();
        foreach ($treeObject->fetchTree() as $category){
            $data[$category->id] = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;',$category->level) . $category->title;
        }
        return $data;
    }

    static public function addCategoriesToNavigation($navigation, $category_id)
    {
        $category = Doctrine::getTable('Catalog_Model_Category')->find($category_id);
        $ancestors = $category->getNode()->getAncestors();
        $oldPage = $navigation->findOneBy('label', 'Catalog');
        $tmpPages = $oldPage->getPages();
        if ($ancestors) foreach ($ancestors as $ancestor){
            $options = array(
                'label'      => $ancestor->title,
                'module'     => 'catalog',
                'controller' => 'category',
                'action'     => 'admin',
                'params'     =>array('category_id'=> $ancestor->id)
            );
            $oldPage->setOptions($options);
            $newPage = new Zend_Navigation_Page_Mvc();
            $oldPage->addPage($newPage);
            $oldPage = $newPage;
        }
        $options = array(
            'label'      => $category->title,
            'module'     => 'catalog',
            'controller' => 'category',
            'action'     => 'admin',
            'params'     =>array('category_id'=> $category->id)
        );
        $oldPage->setOptions($options);
        $oldPage->setPages($tmpPages);
    }

    public function getForm($category_id = null){
        if ($this->_categoryForm == null){
            $this->_categoryForm = new Catalog_Form_CategoryForm();
            $this->_categoryForm->setDefaults($this->toArray());
        }
        return $this->_categoryForm;
    }

    public function add($data, $parent_id)
    {
        $form = $this->getForm();
        if ($form->isValid( $data )){
            $parentCategory = Doctrine::getTable('Catalog_Model_Category')->find($parent_id);
            $newCategory = new Catalog_Model_Category();
            $newCategory->fromArray($form->getValues());
            $newCategory->getNode()->insertAsLastChildOf($parentCategory);
            return true;
        }
        return false;
    }

    public function edit($data)
    {
        $form = $this->getForm();
        if ($form->isValid( $data )){
            $this->fromArray($form->getValues());
            $this->save();
            return true;
        }
        return false;
    }
    protected $_moveForm = null;

    public function getMoveForm(){
        if ($this->_moveForm == null){
            $this->_moveForm = new Catalog_Form_CategorySelect();
            $this->_moveForm->setDefault('selected_category_id', $this->getNode()->getParent()->id);
        }
        return $this->_moveForm;
    }


    public function move($data)
    {
        $form = $this->getMoveForm();
        if ($form->isValid( $data )){
            $this->fromArray($form->getValues());
            $parent_id = $form->getValue('selected_category_id');
            $newParent = Doctrine::getTable('Catalog_Model_Category')->find($parent_id);
            
            if ( $newParent->getNode()->isDescendantOf($this) ) {
                return false;
            }
            if ( $newParent->getNode()->isEqualTo($this) ) {
                return false;
            }

            $this->getNode()->moveAsLastChildOf($newParent);    
            
            return true;
        }
        return false;
    }


}